/**
 * Amkai Enterprise Solution (AES.) 
 * Copyright 2004-2008 by Amkai(TM), Inc.
 * www.amkai.com
 * 
 * Project: webservice
 * Package: com.amkai.aes.webservice.binary.objecthandler.registration
 * File: EstimatedRevenueHandler.java
 * Created: Mar 23, 2009 1:55:28 PM
 * Author: lkovari 
 * 
 */
package com.amkai.aes.webservice.binary.objecthandler.registration;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;

import com.amkai.aes.aescommon.exceptions.ContractCalculationException;
import com.amkai.aes.aescommon.service.binary.job.registration.EstimatedRevenueJob;
import com.amkai.aes.aescommon.service.result.registration.EstimatedRevenueResult;
import com.amkai.aes.aescommon.service.scheduling.SchedulingResult;
import com.amkai.aes.generatedbeans.billinggroup.BillingGroup;
import com.amkai.aes.generatedbeans.contract.Contract;
import com.amkai.aes.generatedbeans.insurance.InsuranceCarrier;
import com.amkai.aes.generatedbeans.insurance.InsurancePlan;
import com.amkai.aes.generatedbeans.insurance.InsurancePolicyCaseVerifiation;
import com.amkai.aes.generatedbeans.inventory.items.SupplyResourceEquipmentItem;
import com.amkai.aes.generatedbeans.pmcase.PmCase;
import com.amkai.aes.generatedbeans.registration.Patient;
import com.amkai.aes.generatedbeans.scheduling.AbstractAppointment;
import com.amkai.aes.generatedbeans.ui.estimatedrevenue.EstimatedRevenueRow;
import com.amkai.aes.server.manager.EstimatedRevenueJobManager;
import com.amkai.aes.server.scheduling.old.ScheduleTimeProvider;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.rad.designerbase.beans.IStandardRADBean;

/**
 * #6565
 * EstimatedRevenueHandler
 * @author lkovari
 * Description:
 *
 */
public class EstimatedRevenueHandler implements	JobObjectHandler<EstimatedRevenueJob, Serializable, EstimatedRevenueResult> {
	private static final Log log = LogFactory.getLog( EstimatedRevenueHandler.class);
	private boolean isdebugging = false;
	
	@Override
	public EstimatedRevenueResult process(EstimatedRevenueJob job, Serializable object) throws Exception {
		EstimatedRevenueResult estimatedRevenueResult = new EstimatedRevenueResult();

		SessionManager sessionManager = null;
		sessionManager = SiteManager.Start();
		Session session = sessionManager.openSession();
		
		EstimatedRevenueJobManager estimatedRevenueJobManager = new EstimatedRevenueJobManager();
		estimatedRevenueJobManager.setSessionManager(sessionManager);
		//#11600
		estimatedRevenueJobManager.setNeedToSetoToZeroTheContractFee(job.isNeedToSetoToZeroTheContractFee());
		try {
			if (isdebugging)
				System.out.println(">> EstimatedRevenueHandler handle " + job.getEstimatedRevenueJobKind().name());
			switch (job.getEstimatedRevenueJobKind()) {
			case BILLINGGROUPSBYPATIENT : {
				List<BillingGroup> billingGroups = estimatedRevenueJobManager.getBillingGroups(job.getDepartment(), job.getPatient());
				estimatedRevenueResult.setBillingGroups(billingGroups);
				if (isdebugging) 
					System.out.println(">> EstimatedRevenueHandler billingGroups #" + billingGroups.size());
				break;
			}
			case BILLINGGROUP_DETAILS : {
				BillingGroup billingGroup = estimatedRevenueJobManager.getBillingGroup(job.getBillingGroup());
				estimatedRevenueResult.getBillingGroups().clear();
				if (billingGroup != null)
					estimatedRevenueResult.getBillingGroups().add(billingGroup);
				if (isdebugging) 
					if (billingGroup != null)
						System.out.println(">> EstimatedRevenueHandler billingGroup #" + billingGroup.getDescription());
				break;
			}
			case INSURANCECARRIERS : {
				List<InsuranceCarrier> insuranceCarriers = estimatedRevenueJobManager.getInsuranceCarriers(job.getDepartment(), job.getPatient());
				estimatedRevenueResult.setInsuranceCarriers(insuranceCarriers);
				if (isdebugging) 
					System.out.println(">> EstimatedRevenueHandler insuranceCarriers #" + insuranceCarriers.size());
				break;
			}
			case PRIMARYINSURANCECARRIERBYBILLINGGROUP : {
				InsuranceCarrier primaryInsuranceCarrier = estimatedRevenueJobManager.getPrimaryInsuranceCarrierByBillingGroup(job.getBillingGroup());
				if (isdebugging) 
					System.out.println("");
				estimatedRevenueResult.setInsuranceCarrier(primaryInsuranceCarrier);
				if (isdebugging) {
					if (primaryInsuranceCarrier != null)
						System.out.println(">> EstimatedRevenueHandler primaryInsuranceCarrier " + primaryInsuranceCarrier.getName());
					else
						System.out.println(">> EstimatedRevenueHandler primaryInsuranceCarrier not found");
				}
				break;
			}
			case INSURANCEPLANS : {
				List<InsurancePlan> insurancePlans = estimatedRevenueJobManager.getInsurancePlans(job.getDepartment(), job.getPatient());
				estimatedRevenueResult.setInsurancePlans(insurancePlans);
				if (isdebugging) 
					System.out.println(">> EstimatedRevenueHandler insurancePlans #" + insurancePlans.size());
				break;
			}
			case INSURANCEPLANSBYCARRIER : {
				List<InsurancePlan> insurancePlans = estimatedRevenueJobManager.getInsurancePlansByCarrier(job.getInsuranceCarrier());
				estimatedRevenueResult.setInsurancePlans(insurancePlans);
				if (isdebugging) 
					System.out.println(">> EstimatedRevenueHandler insurancePlans #" + insurancePlans.size());
				break;
			}
			case CONTRACTS : {
				List<Contract> contracts = estimatedRevenueJobManager.getContracts(job.getDepartment(), job.getPatient());
				estimatedRevenueResult.setContracts(contracts);
				if (isdebugging) 
					System.out.println(">> EstimatedRevenueHandler contracts #" + contracts.size());
				break;
			}
			case CONTRACTSBYPLAN : {
				List<Contract> contracts = estimatedRevenueJobManager.getContractsByPlan(job.getInsurancePlan());
				estimatedRevenueResult.setContracts(contracts);
				if (isdebugging) 
					System.out.println(">> EstimatedRevenueHandler contracts #" + contracts.size());
				break;
			}
			case CALCULATE_ESTIMATEDREVENUE : {
				List<EstimatedRevenueRow> estimatedRevenueRows = null;
				//#13026
				try {
					estimatedRevenueRows = estimatedRevenueJobManager.getEstimatedRevenue(
							sessionManager,
							job.getDepartment(),
							//#13803
//							reload(sessionManager, AbstractAppointment.class, job.getAbstractAppointment()), 
							job.getAbstractAppointment(),							
							reload(sessionManager, PmCase.class, job.getPmCase()),
							reload(sessionManager, Patient.class, job.getPatient()), 
							reload(sessionManager, BillingGroup.class, job.getBillingGroup()), 
							reload(sessionManager, InsuranceCarrier.class, job.getInsuranceCarrier()), 
							reload(sessionManager, InsurancePlan.class, job.getInsurancePlan()), 
							reload(sessionManager, Contract.class, job.getContract())
						);
					estimatedRevenueResult.setEsimatedRevenueRows(estimatedRevenueRows);
				}
				catch (ContractCalculationException cce) {
					estimatedRevenueResult.setException(cce);
				}
				//
				break;
			}
			case VERIFICATION_INFO : {
				InsurancePolicyCaseVerifiation insurancePolicyCaseVerification = estimatedRevenueJobManager.getInsurancePolicyCaseVerification(job.getPmCase(), job.getInsurancePolicy());
				estimatedRevenueResult.setInsurancePolicyCaseVerification(insurancePolicyCaseVerification);
				break;
			}
			//#13648
			case EQUIPMENTITEMBYEQUIPMENTREFERENCE : {
				List<SupplyResourceEquipmentItem> supplyResourceEquipmentItems = estimatedRevenueJobManager.downloadSupplyResourceEquipmentItems(job.getEquipmentReferenceIds(), job.getDepartment());
				estimatedRevenueResult.setSupplyResourceEquipmentItems(supplyResourceEquipmentItems);
			}
			}
		}
		catch (Exception e) {
			log.error("Exception in EstimatedRevenueHandler at " + job.getEstimatedRevenueJobKind().name(), e);
			throw e;
		}
		finally {
			estimatedRevenueJobManager = null;
			sessionManager.closeSession();
		}
		return estimatedRevenueResult;
	}
	
	private final <T extends IStandardRADBean> T reload(SessionManager sm, Class<T> type, T object) throws Exception {
		if (object!=null) {
			object = sm.get(type, object.getId());
		}
		return object;
	}

}
